// 基础版：scoreManager.js（无加密依赖，直接运行）
const db = uniCloud.database();
const _ = db.command; // 引入数据库操作符（用于日期筛选等）

/**
 * 积分管理云函数
 * @param {Object} event - 入参
 * @param {String} event.action - 操作类型：daily_sign/post_create/task_complete/get_records/task_evaluation_reward
 * @param {String} event.userId - 用户ID（必填）
 * @param {Object} [event.data] - 附加数据（如任务ID、帖子ID等）
 * @param {Object} context - 上下文（无需修改）
 */
exports.main = async (event, context) => {
  const action = event.action;
  const userId = event.userId;
  const data = event.data || {};
  
  if (!userId) {
    return { code: 400, msg: "用户ID不能为空" };
  }
  
  if (!action) {
    return { code: 400, msg: "操作类型不能为空" };
  }
  
  try {
    if (action === "daily_sign") {
      return await handleDailySign(userId);
    } else if (action === "post_create") {
      return await handlePostCreate(userId, data);
    } else if (action === "post_like") {
      return await handlePostLike(userId, data);
    } else if (action === "task_complete") {
      return await handleTaskComplete(userId, data);
    } else if (action === "task_evaluation_reward") {
      return await handleTaskEvaluationReward(userId, data);
    } else if (action === "get_records") {
      return await getScoreRecords(userId, data);
    } else {
      return { code: 400, msg: "未知操作类型" };
    }
  } catch (error) {
    console.error("积分管理失败:", error);
    return { code: 500, msg: "操作失败", error: error.message };
  }
};

async function handleDailySign(userId) {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const tomorrow = new Date(today);
  tomorrow.setDate(tomorrow.getDate() + 1);
  
  const signRecord = await db.collection("user-score")
    .where({
      user_id: userId,
      type: "daily_sign",
      create_time: db.command.gte(today).and(db.command.lt(tomorrow))
    })
    .get();
  
  if (signRecord.data.length > 0) {
    return { code: 400, msg: "今日已签到" };
  }
  
  return await addScoreRecord(userId, "daily_sign", 5, "每日签到");
}

async function handlePostCreate(userId, data) {
  const postId = data.postId;
  if (!postId) {
    return { code: 400, msg: "帖子ID不能为空" };
  }
  
  const existRecord = await db.collection("user-score")
    .where({
      user_id: userId,
      type: "post_create",
      related_id: postId
    })
    .get();
  
  if (existRecord.data.length > 0) {
    return { code: 400, msg: "该帖子已获取过积分" };
  }
  
  return await addScoreRecord(userId, "post_create", 10, "发布帖子", postId);
}

async function handlePostLike(userId, data) {
  const postId = data.postId;
  const likerId = data.likerId;
  
  if (!postId) {
    return { code: 400, msg: "帖子ID不能为空" };
  }
  
  // 检查今日是否已获得该帖子的点赞积分（避免重复）
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const tomorrow = new Date(today);
  tomorrow.setDate(tomorrow.getDate() + 1);
  
  const existRecord = await db.collection("user-score")
    .where({
      user_id: userId,
      type: "post_like",
      related_id: postId,
      create_time: db.command.gte(today).and(db.command.lt(tomorrow))
    })
    .get();
  
  if (existRecord.data.length > 0) {
    return { code: 400, msg: "今日已获得该帖子的点赞积分" };
  }
  
  return await addScoreRecord(userId, "post_like", 2, "帖子获赞", postId);
}

async function handleTaskComplete(userId, data) {
  const taskId = data.taskId;
  const taskTitle = data.taskTitle || "未知任务";
  const score = data.score || 10;
  
  if (!taskId) {
    return { code: 400, msg: "任务ID不能为空" };
  }
  
  const existRecord = await db.collection("user-score")
    .where({
      user_id: userId,
      type: "task_complete",
      related_id: taskId
    })
    .get();
  
  if (existRecord.data.length > 0) {
    return { code: 400, msg: "该任务已获取过积分" };
  }
  
  return await addScoreRecord(userId, "task_complete", score, "完成任务: " + taskTitle, taskId);
}

// 新增：处理任务评价奖励
async function handleTaskEvaluationReward(userId, data) {
  const taskId = data.taskId;
  const taskTitle = data.taskTitle || "未知任务";
  const rating = data.rating;
  const evaluatorId = data.evaluatorId;
  const score = data.score || (rating * 10);
  
  if (!taskId) {
    return { code: 400, msg: "任务ID不能为空" };
  }
  
  if (!rating) {
    return { code: 400, msg: "评价星级不能为空" };
  }
  
  // 检查是否已经获得过该任务的评价奖励
  const existRecord = await db.collection("user-score")
    .where({
      user_id: userId,
      type: "task_evaluation_reward",
      related_id: taskId
    })
    .get();
  
  if (existRecord.data.length > 0) {
    return { code: 400, msg: "该任务已获得过评价奖励" };
  }
  
  const description = `任务评价奖励 (${rating}星评价)`;
  return await addScoreRecord(userId, "task_evaluation_reward", score, description, taskId);
}

async function getScoreRecords(userId, data) {
  const type = data.type || "";
  const page = data.page || 1;
  const pageSize = data.pageSize || 20;
  
  let query = db.collection("user-score").where({ user_id: userId });
  
  if (type) {
    query = query.where({ type: type });
  }
  
  const skipCount = (page - 1) * pageSize;
  
  const recordsRes = await query.orderBy("create_time", "desc").skip(skipCount).limit(pageSize).get();
  const totalRes = await query.count();
  
  const totalScoreRes = await db.collection("user-score").where({ user_id: userId }).get();
  const totalScore = totalScoreRes.data.reduce(function(sum, item) { return sum + item.score; }, 0);
  
  return {
    code: 200,
    msg: "获取成功",
    data: {
      records: recordsRes.data,
      total: totalRes.total,
      page: page,
      pageSize: pageSize,
      totalScore: totalScore
    }
  };
}

async function addScoreRecord(userId, type, score, description, relatedId) {
  const now = new Date();
  const expireTime = new Date(now.getTime() + 365 * 24 * 60 * 60 * 1000); // 1年后过期
  
  const scoreRecord = {
    user_id: userId,
    type: type,
    score: score,
    description: description,
    related_id: relatedId || null,
    create_time: now.getTime(), // 使用时间戳
    expire_time: expireTime.getTime() // 使用时间戳
  };
  
  const insertRes = await db.collection("user-score").add(scoreRecord);
  
  const totalScoreRes = await db.collection("user-score").where({ user_id: userId }).get();
  const totalScore = totalScoreRes.data.reduce(function(sum, item) { return sum + item.score; }, 0);
  
  return {
    code: 200,
    msg: "积分添加成功",
    data: {
      recordId: insertRes.id,
      currentScore: score,
      totalScore: totalScore,
      description: description
    }
  };
}